﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using WTwitter.Model.Framework;
using WTwitter.Model.Framework.TextSplitter;
using System.Globalization;

namespace WTwitter.Model.SearchTwitter {
	/// <summary>
	/// Search APIから取得した１つぶやきを表すクラス
	/// </summary>
	class SearchTwitterItem : ITimelineItem {

		#region private member
		private Status _item;
		private string _text;
		private string _detailDescription;
		private string _source;
		private List<TextComponent> _textComponents;
		private IUser _user;
		#endregion

		public SearchTwitterItem(Status item) {
			_item = item;
			_user = new SearchTwitterUser(item);
		}

		#region ITimelineItem メンバ

		public ItemType Type {
			get { return ItemType.SearchTwitter; }
		}

		public string TypeOfSourceTimeline {
			get { return "Twitter Search API"; }
		}

		public long Id {
			get { return _item.Id; }
		}

		public IUser User {
			get { return _user; }
		}

		public long? InReplyTo {
			get { return null; }
		}

		public string Text {
			get {
				if (string.IsNullOrEmpty(_text)) {
					_text = HttpUtility.HtmlDecode(_item.Text);
				}
				return _text;
			}
		}

		private DateTime? _createdAt = null;
		public DateTime CreatedAt {
			get {
				//文字列で取得したものをDateTimeに変換する
				if (_createdAt == null) {
					_createdAt = DateTime.ParseExact(CreatedAtString, "ddd, dd MMM yyyy HH:mm:ss zzzz",
						CultureInfo.GetCultureInfoByIetfLanguageTag("en-us"));
				}
				return _createdAt.Value;
			}
		}

		public string CreatedAtString {
			get { return _item.CreatedAtString; }
		}

		public long? ToUserId {
			get { return _item.ToUserId; }
		}

		public string ToUser {
			get { return _item.ToUser; }
		}

		public string Source {
			get {
				if (string.IsNullOrEmpty(_source)) {
					_source = HttpUtility.HtmlDecode(_item.Source);
				}
				return _source;
			}
		}

		public List<TextComponent> TextComponents {
			get {
				if (_textComponents == null) {
					_textComponents = Splitter.Split(Text);
				}
				return _textComponents; 
			}
		}

		public string DetailDescription {
			get {
				if (string.IsNullOrEmpty(_detailDescription)) {
					_detailDescription = string.Format(
						"Id: {1}{0}ScreenName: {2}{0}Name: {3}{0}FromUserId: {4}{0}CreatedAt: {5}{0}"
						+ "Source: {6}{0}ToUser: {7}{0}ToUserId: {8}{0}",
						Environment.NewLine,
						Id,
						User.ScreenName,
						User.Name,
						User.Id.ToString(),
						CreatedAtString,
						Source,
						ToUser,
						ToUserId.ToString()
						);
				}
				return _detailDescription;
			}
		}

		public bool Favorited {
			get { return false; }
		}
		#endregion


		#region IEquatable<ITimelineItem> メンバ

		public bool Equals(ITimelineItem other) {
			return this.Id == other.Id;
		}

		#endregion
	}
}
